import React from 'react';
import { Popover, Button, Icon, Tag } from 'antd';
import connectFn from '@/utils/connectFn';
import Mixins from '@/components/Common/mixin';
import CreateTable from '@/components/CreateTable';
import { StateType } from '@/common-typings';
import TableTool, { WithLinkAuth } from '@/components/CreateTable/TableTool';
import SetTimeoutManager from '@/utils/setTimeoutManager';
import Observer from '@/utils/observer';
import constant from '@/const';

@connectFn(['exportExcel'])
class Export extends Mixins {
  state = {
    visible: false,
  };

  componentDidMount(): void {
    this.initRequest();

    // 绑定全局事件
    Observer.off('get-export-download-list').on('get-export-download-list', () => {
      // 判断是否打开了下载列表；
      if (!this.state.visible) {
        this.handleVisibleChange(true);
      } else {
        // 如果是打开的，立即在请求一次；
        this.initRequest();
      }
    });
  }

  /**
   * 切换显示隐藏
   * @param visible
   */
  handleVisibleChange = (visible: boolean) => {
    this.setState({ visible }, () => {
      if (this.state.visible) {
        this.initRequest();

        // 若用户一直显示该下载列表，则开启5s轮询数据查询
        SetTimeoutManager.addSetTimeout(
          'exportManager',
          this.initRequest.bind(this),
        ).startSetTimout('exportManager', 5000);
      } else {
        // 当用户关闭时停止计时器
        SetTimeoutManager.stopSetTimeout('exportManager');
      }
    });
  };

  /**
   * 请求数据
   */
  initRequest = () => {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'exportExcel/getExportManageList',
        payload: {},
      });
    }
  };

  /**
   * 点击删除
   * @param param
   */
  handleDelete = (param: StateType) => {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'exportExcel/clearExportManageById',
        payload: { id: param.id },
        fn: () => {
          this.initRequest();
        },
      });
    }
  };

  /**
   * 清除所有
   */
  clearAll = () => {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'exportExcel/clearExportManageAll',
        payload: {},
        fn: () => {
          this.initRequest();
          this.handleVisibleChange(false);
        },
      });
    }
  };

  render() {
    const { exportExcel } = this.props;
    const getTableData = () => {
      exportExcel.downloadList.forEach((item: StateType, index: number) => {
        item.index = index + 1;
      });
      const tableConfig = {
        data: exportExcel.downloadList,
        header: [
          {
            title: '序号',
            dataIndex: 'index',
            width: 80,
          },
          {
            title: '文件名',
            dataIndex: 'title',
          },
          {
            title: '创建日期',
            dataIndex: 'createDate',
            // @ts-ignore 此方法存在与数据劫持中，能够获取到方法
            render: (text: number | string) => this.getFormatDate(text, true),
          },
          {
            title: '状态',
            dataIndex: 'status',
            width: 100,
            render: (text: number) => {
              let result = null;
              constant.GLOBAL_EXPORT_STATUS.forEach(item => {
                if (text === item.value) {
                  result = <Tag color={item.color}>{item.label}</Tag>;
                }
              });
              return result;
            },
          },
          {
            title: '操作',
            dataIndex: 'operates',
            render: (row: string, record: StateType) => {
              const tableToolOptions = [
                {
                  name: '下载',
                  auth: record.status === 1,
                  href: record.filePath || 'javescript:',
                  download: `${record.title}.csv`,
                  event: {
                    // click: this.handleDownLoad.bind(this, row),
                  },
                },
                {
                  name: '删除',
                  auth: true,
                  event: {
                    click: this.handleDelete.bind(this, record),
                  },
                },
              ];
              return <TableTool options={tableToolOptions} isCenter />;
            },
          },
        ],
      };
      return <CreateTable tableConfig={tableConfig} />;
    };

    return (
      <Popover
        content={getTableData()}
        title={
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span>下载列表</span>
            <WithLinkAuth auth onClick={this.clearAll}>
              全部清除
            </WithLinkAuth>
          </div>
        }
        trigger="click"
        placement="bottomRight"
        visible={this.state.visible}
        onVisibleChange={this.handleVisibleChange}
      >
        <Button type="primary" size="small">
          {`下载列表(${exportExcel.downloadList.length})`}
          <Icon type="down" style={{ fontSize: '10px' }} />
        </Button>
      </Popover>
    );
  }
}

export default Export;
